<template>
  <div class="materials-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">物料管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="materials" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="物料"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增物料
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.name" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.code" placeholder="请输入物料编码" clearable />
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="原材料" value="raw" />
            <el-option label="半成品" value="semi" />
            <el-option label="成品" value="finished" />
            <el-option label="辅料" value="auxiliary" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchEnable">批量启用</el-button>
              <el-button size="small" type="warning" @click="handleBatchDisable">批量停用</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="code" label="物料编码" width="150" />
        <el-table-column prop="name" label="物料名称" width="200" />
        <el-table-column prop="type" label="物料类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="spec" label="规格型号" width="150" />
        <el-table-column prop="unit" label="基本单位" width="100" />
        <el-table-column prop="category" label="物料分类" width="120" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="costPrice" label="成本价" width="100">
          <template #default="{ row }">
            {{ row.costPrice ? '¥' + row.costPrice.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="salePrice" label="销售价" width="100">
          <template #default="{ row }">
            {{ row.salePrice ? '¥' + row.salePrice.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.stock < row.minStock ? 'danger' : 'success'">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="info" @click="handleViewBOM(row)">BOM</el-button>
            <el-button link type="success" @click="handleViewPrice(row)">价格</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="800px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option label="原材料" value="raw" />
                <el-option label="半成品" value="semi" />
                <el-option label="成品" value="finished" />
                <el-option label="辅料" value="auxiliary" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料分类" prop="category">
              <el-input v-model="form.category" placeholder="请输入分类" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本单位" prop="unit">
              <el-select v-model="form.unit" placeholder="选择单位">
                <el-option label="件" value="件" />
                <el-option label="个" value="个" />
                <el-option label="kg" value="kg" />
                <el-option label="米" value="米" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :min="0" :precision="2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number v-model="form.salePrice" :min="0" :precision="2" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全库存" prop="minStock">
              <el-input-number v-model="form.minStock" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大库存" prop="maxStock">
              <el-input-number v-model="form.maxStock" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="物料图片" prop="image">
          <el-input v-model="form.image" placeholder="请输入图片URL" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  type: ''
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'code', label: '物料编码' },
  { prop: 'name', label: '物料名称' },
  { prop: 'type', label: '物料类型' },
  { prop: 'spec', label: '规格型号' },
  { prop: 'unit', label: '基本单位' },
  { prop: 'costPrice', label: '成本价' },
  { prop: 'salePrice', label: '销售价' },
  { prop: 'stock', label: '库存' }
]

// 表格数据
const tableData = ref([
  { 
    id: 1, code: 'MAT001', name: 'iPhone 15', type: 'finished', spec: '128GB 黑色', 
    unit: '台', category: '手机', brand: '苹果', supplier: '富士康',
    costPrice: 4500, salePrice: 5999, stock: 120, minStock: 50, maxStock: 500, status: 1
  },
  { 
    id: 2, code: 'MAT002', name: 'OLED屏幕', type: 'raw', spec: '6.1英寸', 
    unit: '片', category: '显示屏', brand: '三星', supplier: '三星显示',
    costPrice: 800, salePrice: 0, stock: 300, minStock: 100, maxStock: 1000, status: 1
  },
  { 
    id: 3, code: 'MAT003', name: 'A17芯片', type: 'raw', spec: '3nm工艺', 
    unit: '颗', category: '芯片', brand: '台积电', supplier: 'TSMC',
    costPrice: 1200, salePrice: 0, stock: 200, minStock: 80, maxStock: 800, status: 1
  },
  { 
    id: 4, code: 'MAT004', name: '电池组件', type: 'raw', spec: '3349mAh', 
    unit: '个', category: '电池', brand: 'ATL', supplier: '新能源',
    costPrice: 150, salePrice: 0, stock: 500, minStock: 200, maxStock: 2000, status: 1
  },
  { 
    id: 5, code: 'MAT005', name: '包装盒', type: 'auxiliary', spec: '标准包装', 
    unit: '个', category: '包材', brand: '自有', supplier: '包装厂',
    costPrice: 15, salePrice: 0, stock: 1000, minStock: 500, maxStock: 5000, status: 1
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 5
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增物料')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  type: '',
  spec: '',
  unit: '',
  category: '',
  brand: '',
  supplier: '',
  costPrice: 0,
  salePrice: 0,
  minStock: 0,
  maxStock: 0,
  image: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择物料类型', trigger: 'change' }],
  unit: [{ required: true, message: '请选择基本单位', trigger: 'change' }]
}

// 获取类型标签
const getTypeTag = (type) => {
  const tagMap = {
    raw: 'primary',
    semi: 'warning',
    finished: 'success',
    auxiliary: 'info'
  }
  return tagMap[type] || ''
}

// 获取类型名称
const getTypeLabel = (type) => {
  const labelMap = {
    raw: '原材料',
    semi: '半成品',
    finished: '成品',
    auxiliary: '辅料'
  }
  return labelMap[type] || type
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.type = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量操作
const handleBatchEnable = () => {
  ElMessage.success('批量启用成功')
  selectedRows.value = []
}

const handleBatchDisable = () => {
  ElMessage.success('批量停用成功')
  selectedRows.value = []
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个物料吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增物料'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    type: '',
    spec: '',
    unit: '',
    category: '',
    brand: '',
    supplier: '',
    costPrice: 0,
    salePrice: 0,
    minStock: 0,
    maxStock: 0,
    image: '',
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑物料'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 提交
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除物料 "${row.name}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 查看BOM
const handleViewBOM = (row) => {
  router.push({ path: '/basedata/bom', query: { materialId: row.id } })
}

// 查看价格
const handleViewPrice = (row) => {
  router.push({ path: '/basedata/prices', query: { materialId: row.id } })
}
</script>

<style scoped>
.materials-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

